package coop.bancocredicoop.proyectos.gd.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import coop.bancocredicoop.proyectos.gd.Usuario;
import coop.bancocredicoop.proyectos.gd.alfresco.AlfrescoHttpClient;
import coop.bancocredicoop.proyectos.gd.alfresco.Utils;
import coop.bancocredicoop.proyectos.gd.domain.Document;
import coop.bancocredicoop.proyectos.gd.service.DocumentService;

public class DocumentOpenerFromRepository extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(DocumentOpenerFromRepository.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Long documentId = Long.parseLong(request.getParameter("documentId"));
        AlfrescoHttpClient alfrescoClient = Utils.getAlfrescoClientFromConfigAsUser(
        		((Usuario)request.getSession().getAttribute("usuario")).getUserName());
        DocumentService documentService = new DocumentService();
        Document documentInstance = documentService.getDocumentById(documentId);
        
        if (documentInstance.getDeleteDate() != null) {
        	response.getWriter().print("Este documento ha sido eliminado.");
        	response.getWriter().close();
        	return;
        }
        
        try {
			alfrescoClient.getContent(documentInstance, response.getOutputStream());
		} catch (Exception e) {
			log.error(String.format("Error downloading document: %s", documentId), e);
		} finally {
			response.getOutputStream().close();	
		}
        
   }
	
}
